<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/8/7
 * Time: 15:33
 */

namespace app\api\controller;

use think\Controller;
use app\common\controller\Api;
use app\wap\controller\Notify as WapNotify;
use app\api\controller\OssController as OSSApi;
use think\Exception;
use think\Request;
use think\Validate;


class Common extends Api
{

    public function upload()
    {
        header('Access-Control-Allow-Origin:*');

        $module='admin';
        $use='admin_thumb';
        $data = [];
        $file = request()->file("file");
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $module . DS . $use);
            if($info){
                $object = 'custom/'.md5($info->getSaveName().time()).".jpg";//想要保存文件的名称
                $file = ROOT_PATH  . 'public'  . DS . 'uploads' . DS . $module . DS . $use . DS . $info->getSaveName();//文件路径，必须是本地的
                try{
                    $OssController = new OSSApi();
                    $ossClient = $OssController->newOssClient();
                    $ossClient->uploadFile($OssController->bucket,$object,$file);
                    // 删除本地文件
                    unlink($file);
                    // 定义全局变量存储图片的oss路径
                    $config=config('aliyun_oss');
                    $ossimgurl = "https://".$OssController->bucket.".".$config['endpoint']."/".$object;
                    $res=[
                        'code'=>0,
                        'src'=>$ossimgurl
                    ];
                } catch(\Exception $e) {
                    $res=[
                        'code'=>401,
                        'msg'=>"上传失败".$e
                    ];
                }

                return json_encode($res);
            }else{
                // 上传失败获取错误信息
                return $file->getError();
            }
        }
    }

    static function http($url, $method = "GET", $postfields = NULL, $headers = array())
    {
        try {
            $ssl = stripos($url, 'https://') === 0 ? true : false;
            $ci = curl_init();
            /* Curl settings */
            curl_setopt($ci, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); //在HTTP请求中包含一个"User-Agent: "头的字符串。
            curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ci, CURLOPT_TIMEOUT, 30);
            curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ci, CURLOPT_ENCODING, "");
            if ($ssl) {
                curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
                curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
            }
            curl_setopt($ci, CURLOPT_HEADER, FALSE);

            switch ($method) {
                case 'POST':
                    curl_setopt($ci, CURLOPT_POST, TRUE);
                    if (!empty($postfields)) {
                        curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                    }
                    break;
            }

            curl_setopt($ci, CURLOPT_URL, $url);
            curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE);

            $response = curl_exec($ci);
            $httpCode = curl_getinfo($ci, CURLINFO_HTTP_CODE);
            $httpInfo = curl_getinfo($ci);

            if (FALSE === $response)
                throw new \Exception(curl_error($ci), curl_errno($ci));
        } catch (\Exception $e) {
            throw $e;
        }

        curl_close($ci);
        return $response;
    }

    //发送报警邮件
    public function sendNoticeMailToKbx($subject='产品问题【测试】',$address='david@kuaibangxing.com',$content)
    {
        (new WapNotify())->kbxemailcode($subject,$content,$address);
    }

    //获取当前可用的城市列表
    public function getSoftCityList()
    {
        //小程序展示的城市
        $list = db('city')->field('id,name,eng_name')->where([
            'wxx_recommend'=>1,
            'deleted'=>0,
            'groupid'=>['gt',0]//非国家
        ])->order('groupid asc,id asc')->select();
        //增加其他城市选择
        array_push($list,['id'=>99999,'name'=>'其他','eng_name'=>'other']);
        return $list;
    }

    //隐藏较长字符的中间部分
    public function hideLongStringMiddlePart($string)
    {
        $length = mb_strlen($string);
        switch ($length){
            case 0:
            case 1:
                break;
            case 2:
            case 3:
                $star_length = min($length-1,4);
                $star_string = str_repeat('*',$star_length);
                $string = str_replace(mb_substr($string,1,$length-1),$star_string,$string);
                break;
            default:
                $star_length = min($length-2,4);
                $star_string = str_repeat('*',$star_length);
                $string = str_replace(mb_substr($string,1,$length-2),$star_string,$string);
                break;
        }

        return $string;
    }

    //判断是否开启拼游邮件提醒
    public function checkFreeGroupSendNoticeEmail()
    {
        $config = db('webconfig')->where('web','web')->find();
        if(empty($config) || empty($config['grouptour_notice_email'])) return false;
        return true;
    }

    //获取货币类型
    public function getCurrencyListByCity($field='currency_name,currency_code,currency_symbol'){
        return db('city')->where('groupid',0)->field($field)->select();
    }

    //获取'currency_code'=>'currency_symbol'数组
    public function getCurrencySymbols()
    {
        $currencyData = $this->getCurrencyListByCity();
        if(empty($currencyData)) return [];
        $result = [];
        foreach ($currencyData as $k=>$v){
            if(!empty($v['currency_code'])) $result[$v['currency_code']] = $v['currency_symbol'] ?? '';
        }
        return $result;
    }
    //获取货币类型
    public function getCurrencyListByCityId($cityId,$field='currency_name,currency_code,currency_symbol'){
        if(empty($cityId)) return [];
        $city = db('city')->find($cityId);
        if(empty($city)) return [];
        if($city['groupid']>0){
            $city = db('city')->find($city['groupid']);
            if(empty($city) || $city['groupid']>0) return [];
        }
        return $city;
    }

    //商品上架发送通知到微信群
    public function sendUpGoodsMsgToWx($goods_id,$admin_id,$platform)
    {
        $where['g.goods_id'] = $goods_id;
        $goods = db('goods g')
            ->join('city c','c.id=g.city_id','left')
            ->join('product p','p.item_num=g.goods_tcode','left')
            ->field('g.goods_id,g.goods_name,p.name as product_name,
            c.name as city_name,g.supplier_id,g.goods_tcode')
            ->where($where)
            ->find();
        if(empty($goods_id) || empty($goods)) return false;

        $supplier_name = '';
        $supplierList = $this->getSupplierList();
        foreach ($supplierList as $supplier){
            if($goods['supplier_id']==$supplier['id']){
                $supplier_name = $supplier['name'];break;
            }
        }
        $adminInfo = $this->getAdminInfo($admin_id);
        $product_name = empty($goods['product_name'])?(empty($goods['goods_name'])?'':$goods['goods_name']):$goods['product_name'];
        $data = [
            'product'=>[
                'code'=>$goods['goods_tcode'],
                'city'=>$goods['city_name'],
                'supplier'=>$supplier_name,
                'adminName'=>$adminInfo['nickname']??'',
                'productName'=>$product_name,
                'platform'=>$platform,
            ]
        ];
        (new KbxOrder())->sendNewProductounding($data);
    }

    public function getSupplierList()
    {
        //供应商
        $KbxOther = new KbxOther();
        $supplierArr = $KbxOther->kbx_suppliers_list();
        //增加自营和其他
        array_unshift($supplierArr,['id'=>'1000000','name'=>'其他']);
        array_unshift($supplierArr,['id'=>'999999','name'=>'自营']);
        return $supplierArr;
    }
    //定制系统管理员表
    public function getAdminInfo($admin_id)
    {
        return db('admin')->find($admin_id);
    }
    //供应商管理员表
    public function getSupplierAdminInfo($admin_id)
    {
        return db('supplier_admin')->find($admin_id);
    }

    public function getSupplierAdminIdsByCompanyId($company_id)
    {
        $where['is_use'] = 1;
        $where['company_id'] = $company_id;
        return db('supplier_admin')->where($where)->column('supplier_admin_id');
    }
    //判断地址是否启用了代理
    public function isOpenVpn()
    {
        $ip = request()->ip();
        $url = 'http://freeapi.ipip.net/'.$ip;
        $result = (new Common())->http($url);
        $result = json_decode($result,true);
        //结果为数组 1 国家定位不在中国 2国家定位在中国香港
        if(is_array($result) && !empty($result[0]) && !empty($result[1])){
            if($result[0]!='中国'){
                return true;
            }else{
                if($result[1]=='香港'){
                    return true;
                }
            }
        }
        //其他情况视为国内用户
        return false;
    }
    /////////////////////////////////////////////////////////////
    //                         谷歌地图                         //
    ////////////////////////////////////////////////////////////
    //谷歌地图接口获取地图列表
    public function getGoogleAddressList()
    {
        $post = request()->post();
        $address = $post['address']??'';
        if(empty($address)) return $this->result('请填写关键字',[],0,'json');
        $result = (new GoogleMap())->getAddressInfo($address);
        $result = json_decode($result,true);
        if(!is_array($result)){
            return $this->result($result,[],-1,'json');
        }else{
            $result['google_map_img'] = '';
            $getMap = $post['getMap']??false;
            if(!empty($getMap)){
                $lat = $result['candidates'][0]['geometry']['location']['lat']??'';
                $lng = $result['candidates'][0]['geometry']['location']['lng']??'';
                $zoom = $post['zoom']??13;
                if(!empty($lat) && !empty($lng)){
                    $google_map_img = (new GoogleMap())->getGoogleMapImgByPoint($lat,$lng,$zoom);
                    $result['google_map_img'] = (new OSSApi())->saveRemoteImgToOSS($google_map_img);
                }
            }

            return $this->result('success',$result,200,'json');
        }
    }


    //根据经纬度获取图片地址
    public function getGoogleImgByLatLng()
    {
        $post = request()->post();
        $lat = $post['lat']??'';
        $lng = $post['lng']??'';
        if(empty($lat) || empty($lng)) return $this->result('缺少经纬度数据',[],-1,'json');
        $zoom = $post['zoom']??13;
        $google_map_img = (new GoogleMap())->getGoogleMapImgByPoint($lat,$lng,$zoom);
        $result['google_map_img'] = (new OSSApi())->saveRemoteImgToOSS($google_map_img);
        return $this->result('success',$result,200,'json');
    }

    /////////////////////////////////////////////////////////////
    //                        高德地图                         //
    ////////////////////////////////////////////////////////////
    //获取高德地图的地址图片
    public function getAMapImgByLocation($location,$width=640,$height=400,$scale=1,$zoom=11)
    {
        if(empty($location)) return "";
        $key = '3aa6da9e057746239b782ab809297d2c';
        $amap_img_url = 'https://restapi.amap.com/v3/staticmap?location='.$location.'&zoom='.$zoom.'&size='.$width.'*'.$height.'&scale='.$scale.'&markers=large,0x008000,:'.$location.'&key='.$key;
        return (new OSSApi())->saveRemoteImgToOSS($amap_img_url);
    }
    //谷歌地图接口获取地图列表
    public function getAmapAddressList()
    {
        $post = request()->post();
        $address = $post['address']??'';
        if(empty($address)) return $this->result('请填写关键字',[],0,'json');
        $result = (new Amap())->getAddressInfo($address);
        $result = json_decode($result,true);
        if(!is_array($result)){
            return $this->result($result,[],-1,'json');
        }else{
            $result['google_map_img'] = '';
            $getMap = $post['getMap']??false;
            if(!empty($getMap)){
                $location = $result['geocodes'][0]['location'];
                $location_arr = explode(',',$location);
                $lat = $location_arr[1]??'';
                $lng = $location_arr[0]??'';
                $zoom = $post['zoom']??11;
                if(!empty($lat) && !empty($lng)){
                    $result['google_map_img'] = $this->getAMapImgByLocation($location,600,300,1,$zoom);
                }
            }

            return $this->result('success',$result,200,'json');
        }
    }

    //根据经纬度获取图片地址
    public function getAmapImgByLatLng()
    {
        $post = request()->post();
        $lat = $post['lat']??'';
        $lng = $post['lng']??'';
        if(empty($lat) || empty($lng)) return $this->result('缺少经纬度数据',[],-1,'json');
        $zoom = $post['zoom']??13;
        $result['google_map_img'] = $this->getAMapImgByLocation($lng.','.$lat,600,300,1,$zoom);
        return $this->result('success',$result,200,'json');
    }

    //获取全部的供应商账号
    public function getAllSupplierList()
    {
        $KbxOther = new KbxOther();
        $supplierArr = $KbxOther->kbx_all_suppliers_list();
        foreach ($supplierArr as $k=>$v) {
            if(empty($v['id']) || empty($v['name'])){
                unset($supplierArr[$k]);
            }
        }

        return $supplierArr;
    }

    //微信公众号图片做代理转发地址
    public function replaceWxImageUrl($content)
    {
        if(empty($content)) return "";
        //去除之前的代理转发
        $content = str_replace('https://www.kuaibangxing.com/transition?img=','',$content);
        //添加http转发
        $content = str_replace('http://mmbiz.qpic.cn/','https://www.kuaibangxing.com/transition?img=http://mmbiz.qpic.cn/',$content);
        //添加https转发
        $content = str_replace('https://mmbiz.qpic.cn/','https://www.kuaibangxing.com/transition?img=https://mmbiz.qpic.cn/',$content);

        return $content;
    }

    //微信公众号图片做代理转发地址
    public function replaceWxSectionLabel($content)
    {
        if(empty($content)) return "";
//        暂不启用
        //$content = str_replace('<section>','<p>',$content);
        //$content = str_replace('</section>','</p>',$content);
        return $content;
    }

    //上传产品附件 新增->product_attachments
    public function uploadProAttachment(Request $request)
    {
        if($request->isPost()){
            $post = $request->post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $validate = new \think\Validate([
                ['file_name', 'require', '文件名不能为空'],
                ['file_url', 'require', '文件地址不能为空'],
                ['product_id', 'require', '产品ID不能为空'],
                ['show_title', 'require', '展示标题不能为空'],
            ]);
            //验证部分数据合法性
            if (!$validate->check($post)) {
                return $this->result('失败：'.$validate->getError(),[],-404,'json');
            }
            $post['create_time'] = time();
            $res = db('product_attachments')->insert($post);
            if($res){
                return $this->result('保存成功',$res,200,'json');
            }else{
                return $this->result('保存失败',[],-404,'json');
            }
        }else{
            return $this->result('请以POST方式上传',[],-404,'json');
        }
    }

    //获取产品附件列表
    public function getProAttachments(Request $request)
    {
        if($request->isPost()){
            $post = $request->post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $validate = new \think\Validate([
                ['product_id', 'require', '产品ID不能为空'],
            ]);
            //验证部分数据合法性
            if (!$validate->check($post)) {
                return $this->result('失败：'.$validate->getError(),[],-404,'json');
            }
            $where['product_id'] = $post['product_id'];
            $where['is_delete'] = 0;
            $result = db('product_attachments')->where($where)->order('create_time desc')->select();
            foreach ($result as $key=>$value){
                $result[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
            }
            return $this->result('成功',$result,200,'json');
        }else{
            return $this->result('请以POST方式上传',[],-404,'json');
        }
    }

    //删除产品附件
    public function delProAttachment(Request $request)
    {
        if($request->isPost()){
            $post = $request->post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $validate = new \think\Validate([
                ['id', 'require', 'ID不能为空'],
            ]);
            //验证部分数据合法性
            if (!$validate->check($post)) {
                return $this->result('失败：'.$validate->getError(),[],-404,'json');
            }
            $where['id'] = $post['id'];
            $res = db('product_attachments')->where($where)->update([
                'is_delete'=>1,
                'delete_time'=>time()
            ]);
            if($res!==false){
                return $this->result('删除成功',$res,200,'json');
            }else{
                return $this->result('删除失败',[],-404,'json');
            }
        }else{
            return $this->result('请以POST方式上传',[],-404,'json');
        }
    }

    //同步产品的附件内容 测试专用
    public function syncProductAttachToTable()
    {
        return '请开启相关功能';exit;
        //查找所有的关联附件的产品
        $data = db('product')->field('id,up_filename,up_url,up_description,up_updatetime')
            ->where('up_url is not null and up_url!=""')->select();
        $attachments = [];
        foreach ($data as $value){
            $attachments[] = [
                'product_id'=>$value['id'],
                'file_name'=>$value['up_filename'],
                'file_url'=>$value['up_url'],
                'create_time'=>$value['up_updatetime']??time(),
                'show_title'=>$value['up_filename'],
                'description'=>$value['up_description'],
            ];
        }
        db()->startTrans();
        try{
            db('product_attachments')->insertAll($attachments);
            db()->commit();
            return 'success';
        }catch (\Exception $e){
            db()->rollback();
            return $e->getMessage();
        }
    }

    //创建产品操作日志
    public function createProductOperationLog($data,$type="")
    {
        if(empty($data['product_id'])
            || empty($data['admin_type'])
            || empty($data['admin_id'])
            || empty($data['operate_url'])
            || empty($data['operate_body'])
        ) return false;

        $data['admin_name'] = $data['admin_type'] == 1 ? $this->getAdminInfo($data['admin_id'])['nickname']??''
                            : $this->getSupplierAdminInfo($data['admin_id'])['supplier_name']??'';
        $data['operate_body'] = json_encode($data['operate_body']);
        $data['create_time'] = time();
        try{
            db('product_operation_log')->insert($data);
        }catch (\Exception $e){
            trace('createProductOperationLog fail,'.$e->getMessage());
        }
    }

    public function addProOperationLogApi(Request $request)
    {
        if($request->isPost()){
            $post = $request->post();
            $validate = new Validate([
                'product_id'=>'require',
                'admin_type'=>'require',
                'admin_id'=>'require',
                'operate_url'=>'require',
                'operate_body'=>'require',
            ],[
                'product_id.require'=>'缺少product_id',
                'admin_type.require'=>'缺少admin_type',
                'admin_id.require'=>'缺少admin_id',
                'operate_url.require'=>'缺少operate_url',
                'operate_body.require'=>'缺少operate_body',
            ]);
            if(!$validate->check($post)){
                return $this->error($validate->getError());
            }
            $this->createProductOperationLog($post,'remote');
        }else{
            return $this->error('请以POST方式提交');
        }
    }

    //获取字符串加密
    public function getEncodeRedirectUrl()
    {
        if(!$this->request->isPost()) return $this->result('请以POST提交',[],-400,'json');
        $openUrl = $this->request->post('openUrl','');
        $tabName = $this->request->post('tabName','');
        $prefix_num = 3;
        if(empty($openUrl)) return $this->result('error',[],-400,'json');
        $prefix = $this->createNoncestr($prefix_num);
        $string = 'openUrl='.$openUrl;
        if(!empty($tabName)) $string .= '&tabName='.$tabName;
        return $this->result('success',[
            'value'=>$prefix . base64_encode(urlencode($string)),
            'prefix_num'=>3
        ],200,'json');
    }

    /**
     *  作用：产生随机字符串，不长于32位
     */
    public function createNoncestr( $length = 32 ){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
}